<template>
  <div>
    <div class="pp-t-96">
      <h3 class="fw-b fs-14">一级分类管理（Standard Message Identifiers，即标准消息标识符SMI）</h3>

      <a-form-model layout="inline" :model="search">

        <!-- 筛选条件与查询 -->

        <a-form-model-item label="">
          <a-input
            v-model="search.name"
            style="width: 321px"
            placeholder="一级分类名称"
          >
            <a-icon slot="suffix" :component="require('@/assets/icon/search.svg')" @click="changeTable({ current: 1})" />
          </a-input>
        </a-form-model-item>

        <a-form-model-item>
          <a-button type="default" ghost :loading="listLoading" @click="resetSearchHandler">
            重置
          </a-button>

        </a-form-model-item>
      </a-form-model>
    </div>

    <!-- table -->
    <div class="pp-rb-box">
      <a-button type="primary" ghost :loading="listLoading" @click="addVisible=true">
        新增一级分类
      </a-button>
      <a-table
        class="table-border mt-16"
        :columns="columns"
        size="middle"
        :data-source="listData"
        :row-key="(row,index) => row.id"
        :pagination="{
          showTotal:(total)=> `共 ${total} 条数据`,
          showSizeChanger: true,//设置每页显示数据条数
          showQuickJumper: true,
          size:'big',
          current:paginationOptions.pageNum,
          pageSize:paginationOptions.pageSize,
          total:paginationOptions.total
        }"
        :loading="listLoading"
        @change="changeTable"
      />
      <!-- <vxe-grid
        ref="xTable1"
        class="event-trigger-packet-upload mt-15"
        show-overflow
        highlight-hover-row
        :columns="columns"
        :data="listData"
        height="640"
        :sort-config="{trigger: 'cell'}"
      /> -->
    </div>
    <!-- add -->
    <a-modal
      v-model="addVisible"
      :mask-closable="false"
      title=""
      :width="520"
      ok-text="确认"
      class="rt-i-modal"
      :dialog-style="{height:'474px'}"
      :centered="addTitle==='新增'"
      :confirm-loading="addRepSmiLoading"
      :footer="addTitle === '查看二级'?null:undefined"
      @ok="addConfirmHandler"
      @cancel="cancelHandler"
    >
      <span slot="closeIcon" class="c-dialog-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

      <div class="c-dialog-title fw-500">{{ addTitle }}分类</div>

      <a-form-model
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        layout="horizontal"
      >
        <a-form-model-item v-if="addTitle !== '查看二级'" label="一级分类名称SMI" prop="name">
          <a-input
            v-model="addForm.name"
            :disabled="addTitle!=='新增一级'"
            class="input-type-o"
            placeholder="一级分类名称SMI"
            style="width: 100%"
          />
        </a-form-model-item>
        <a-form-model-item v-if="addTitle !== '查看二级'" label="中文简称" prop="nameZh">
          <a-input v-model="addForm.nameZh" class="input-type-o" placeholder="中文简称" style="width: 100%" />
        </a-form-model-item>
        <a-form-model-item v-if="addTitle !== '查看二级'" prop="remark">
          <span slot="label">描述<span class="text-color-9ea5b2 fs-12">选填</span></span>
          <a-textarea
            v-model="addForm.remark"
            placeholder="描述"
            style="width: 100%"
            class="input-type-o"
            :auto-size="{ minRows: 5, maxRows: 8 }"
          />
        </a-form-model-item>
        <a-form-model-item v-if="addForm.id">
          <div v-if="addTitle !== '查看二级'" slot="label">
            子分类列表
            <a-popover
              :title="null"
              trigger="click"
              placement="bottom"
              overlay-class-name="fcc-popover"
            >
              <template slot="content">

                <a-select
                  ref="modifyRepSmiByImiRef"
                  v-model="modifyRepSmiByImiSelected"
                  show-arrow
                  style="minWidth: 130px"
                  placeholder="二级分类"
                  @change="(v)=>changeListNotImiHanlder(v,undefined)"
                >
                  <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
                  <a-select-option
                    v-for="item in listNotImiData"
                    :key="item.id"
                    :value="item.name"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </template>
              <a-button
                type="primary"
                ghost
                :loading="modifyRepSmiByImiLoading"
              >
                选择二级分类
              </a-button>
            </a-popover>
          </div>

          <a-spin :spinning="modifyRepSmiByImiLoading" class="beauty-scroll c-vxe-table-style mt-4">
            <vxe-grid
              ref="xTable1"
              stripe
              show-overflow
              highlight-hover-row
              :columns="subclassColumns"
              :data="addForm.relations"
              height="192px"
              :sort-config="{trigger: 'cell'}"
            />
          </a-spin>

        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex';
import rowClass from '@/pages/common/rowClass';
import getSmiAndModel from '../getSmiAndModel';
export default {
  mixins: [rowClass, getSmiAndModel],
  data() {
    return {
      search: {},
      addVisible: false,
      addTitle: '新增一级',
      addForm: {},
      modifyRepSmiByImiVisiable: false,

      modifyRepSmiByImiSelected: undefined,
      addRules: Object.freeze({
        name: [
          { required: true, message: '请填写', trigger: 'change' }
        ],
        nameZh: [
          { required: true, message: '请填写', trigger: 'change' }
        ],
        smi: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      }),
      columns: Object.freeze([
        {
          title: '一级分类名称(SMI)',
          align: 'left',
          dataIndex: 'name',
          customRender: (value) => {
            return value || '';
          }
        },
        {
          title: '一级分类中文简称',
          align: 'left',
          dataIndex: 'nameZh',
          customRender: (value) => {
            return value || '';
          }
        },
        {
          title: 'SMI描述',
          align: 'left',
          dataIndex: 'remark',
          customRender: (value) => {
            return value || '';
          }
        },
        {
          title: '创建人',
          align: 'left',
          dataIndex: 'createBy',
          customRender: (value) => {
            return value || '';
          }
        },
        {
          title: '创建时间',
          align: 'left',
          dataIndex: 'createTime',
          width: 160,
          customRender: (value) => {
            return value ? this.$moment.utc(value) : '--';
          }
        },
        {
          title: '修改人',
          align: 'left',
          dataIndex: 'updateBy',
          width: 100,
          customRender: (value) => {
            return value || '';
          }
        },
        {
          title: '修改时间',
          align: 'left',
          dataIndex: 'updateTime',
          customRender: (value) => {
            return value ? this.$moment.utc(value) : '--';
          }
        },
        {
          title: '操作',
          align: 'left',
          dataIndex: 'option',
          width: 210,
          customRender: (value, record) => {
            const { id } = record;
            return [

              <a-button type='link' onClick={() => this.modifyHandler(record)}>修改</a-button>,
              <a-button type='link' onClick={() => this.modifyHandler(record, 'imi')}>查看二级分类</a-button>,
              <a-popconfirm
                title='确认删除此项?' ok-type='danger'
                ok-text='确认'
                cancel-text='取消'
                onConfirm={() => this.delItemHandler(id)}
              >

                <a-button type='link'>删除</a-button>
              </a-popconfirm>

            ];
          }
        }
      ])

    };
  },
  computed: {
    ...mapState('firstClassClassification', [
      'listLoading',
      'listData',
      'addRepSmiLoading',
      'listNotImiLoading',
      'listNotImiData',
      'modifyRepSmiByImiLoading',
      'listDataModel',
      'paginationOptions'
    ]),
    subclassColumns() {
      return Object.freeze([
        {
          title: '序号',
          align: 'left',
          dataIndex: 'index',
          slots: {
            default: ({ row, rowIndex }) => {
              return rowIndex + 1;
            }
          }
        },
        {
          title: '二级分类名称',
          align: 'left',
          dataIndex: 'imi',
          slots: {
            default: ({ row, rowIndex }) => {
              return row.imi || '--';
            }
          }
        },
        this.addTitle !== '查看二级' ? {
          title: '操作',
          align: 'left',
          dataIndex: 'option',
          width: 100,
          slots: {
            default: ({ row }) => {
              const { id, imi } = row;
              return [
                <a-popconfirm
                  title='确认删除此项?' ok-type='danger'
                  ok-text='确认'
                  cancel-text='取消'
                  onConfirm={() => this.changeListNotImiHanlder(imi, id)}
                >
                  <a-button type='link'>删除</a-button>
                </a-popconfirm>
              ];
            }
          }
        } : ''
      ]);
    }
  },
  mounted() {
    this.changeTable({ current: 1 });
  },
  methods: {
    ...mapMutations('firstClassClassification', [
      'setState'
    ]),
    ...mapActions('firstClassClassification', [
      'getListByName',
      'addRepSmi',
      'deleteRepSmi',
      'modifyRepSmi',
      'getListNotImi',
      'modifyRepSmiByImi'
    ]),
    // 重置
    resetSearchHandler() {
      this.search = {};
      this.changeTable({ current: 1 });
    },
    // 新增/修改
    addConfirmHandler() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (this.addForm.id) {
            this.modifyRepSmi(this.addForm).then((rep) => {
              if (rep) {
                this.addVisible = false;
                this.cancelHandler();
                this.changeTable({ current: 1 });
              }
            });
          } else {
            this.addRepSmi(this.addForm).then((rep) => {
              if (rep) {
                this.addVisible = false;
                this.cancelHandler();
                this.changeTable({ current: 1 });
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // 确认删除
    delItemHandler(id) {
      this.deleteRepSmi({ id }).then((rep) => {
        if (rep) {
          this.changeTable({ current: 1 });
        }
      });
    },
    // 修改预赋值
    modifyHandler(row, flag) {
      this.getListNotImi({ smi: row.name });

      this.addForm = { ...row };

      this.addTitle = '修改一级';
      if (flag === 'imi') {
        this.addTitle = '查看二级';
      }

      this.addVisible = true;
    },
    // 关闭add
    cancelHandler() {
      this.addForm = {};
      this.addTitle = '新增一级';
      this.$refs.addForm.resetFields();
      this.modifyRepSmiByImiSelected = undefined;
    },
    // 删除/修改关联的二级
    changeListNotImiHanlder(imi, id = undefined) {
      this.modifyRepSmiByImiSelected = undefined;
      const smi = this.addForm.name;
      const params = { id, imi, smi };
      this.modifyRepSmiByImi(params).then(async(rep) => {
        if (rep) {
          this.getListNotImi({ smi });
          const newItem = this.listDataModel?.[0]?.relations ?? [];
          this.addForm.relations = [...newItem];
        }
      });
    },
    // 获取table
    getData() {
      this.getListByName(this.search);
    },
    // 翻页
    changeTable({ current, pageSize = 10 }) {
      if (pageSize !== this.paginationOptions.pageSize) {
        current = 1;
      }
      this.setState({ key: 'paginationOptions', payload: { ...this.paginationOptions, pageNum: current, pageSize }});
      this.getData();
    }
  }
};
</script>

<style lang="less">

</style>
